<template>
  <div>
    <div class="item-detail-show">
      <div class="item-detail-left">
        <div class="item-detail-big-img">
          <img :src="pic" alt="">
        </div>
        <div class="item-detail-img-row">
          <div class="item-detail-img-small" v-for="(item, index) in productList" :key="index" @mouseover="showBigImg(item.url)">
            <img :src="item.url" alt="">
          </div>
        </div>
      </div>
      <div class="item-detail-right">
        <div class="item-detail-title">
          <p>{{info.name}}</p>
        </div>
        <div class="item-detail-price-row">
          <div class="item-price-left">
            <div class="item-price-row">
              <p>
                <span class="item-price-title">价格</span>
                <span class="item-price">￥{{info.retailPrice}}</span>
              </p>
            </div>
          </div>
        </div>
        <div class="item-select">
          <div class="item-select-title">
            <p>规格</p>
          </div>
          <div class="item-select-column">
            <div class="item-select-box" v-for="(item, index) in productList" :key="index" @mouseover="showBigImg(item.url)" @click="select(index)" :class="{'item-select-box-active': ((index * 3)) === selectBoxIndex}">
              <div class="item-select-img">
                <img :src="item.url" alt="">
              </div>
              <div class="item-select-intro">
                <p>{{item.specifications}}</p>
              </div>
            </div>
          </div>
        </div>
        <div class="item-select">
          <div class="item-select-title">
            <p>简介</p>
          </div>
          <div class="item-simple">
            <p>{{info.brief===''?'无':info.brief}}</p>
          </div>
        </div>
        <div class="add-buy-car-box">
          <div class="add-buy-car">
            <el-button @click="minus" :disabled="minusListen">-</el-button>
            <el-input class="filter-item" ref="content" v-model.trim="number" :readonly="true" style="width: 110px;" placeholder="商品数量">
            </el-input>
            <el-button @click="add" :disabled="addListen">+</el-button>
            <el-button class="filter-item" type="danger" @click="confirmPay">购买</el-button>
          </div>
        </div>
      </div>
    </div>

    <el-dialog title="确认支付" :visible.sync="dialogChargeFormVisible">
      <el-card class="box-card">
        <h3>确认信息</h3>
        <el-form ref="walletRecoed" :model="walletRecoed" label-position="right" label-width="100px">
          <el-form-item label="订单编号" prop="recordSn">
            <el-input v-model="walletRecoed.recordSn" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="单价（元）" prop="retailPrice">
            <el-input v-model="info.retailPrice" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="规格" prop="specifications">
            <el-input v-model="walletRecoed.specifications" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="数量" prop="number">
            <el-input v-model="number" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="运费" prop="freight">
            <el-input v-model="freight" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item label="总价（元）" prop="modifyAmount">
            <el-input v-model="walletRecoed.modifyAmount" :readonly="true"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card">
        <h3>支付方式</h3>
        <div id="example-4" style="margin-left:50px">
          <template>
            <el-radio v-model="walletRecoed.payType" label="2">
              <img :src="wxpay" alt="" class="abimg">
            </el-radio>
            <el-radio v-model="walletRecoed.payType" label="1" class="rra">
              <img :src="zhifubaopay" alt="" class="abimg">
            </el-radio>
          </template>
        </div>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleChargeCancel">取消</el-button>
        <el-button type="primary" @click="handleCharge" v-bind:disabled="chargeButton">支付</el-button>
      </div>
    </el-dialog>

    <!-- 添加对话框 -->
    <el-dialog title="微信支付" :visible.sync="qrDialogStatus" :close-on-click-modal=false width="250px" @close="handleChargeCancel">
      <vue-qr :text="qrConfig.value" :size="200" :margin="0"></vue-qr>
      <h3 style="color :red">注意：支付过程中，禁止刷新关闭浏览器！支付成功后系统会自动关闭二维码！</h3>
    </el-dialog>
    <!-- 添加对话框 -->
    <el-dialog title="支付宝支付" :visible.sync="alipayDialogStatus" :close-on-click-modal=false width="250px" @close="handleChargeCancel">
      <vue-qr :text="aliQrConfig.value" :size="200" :margin="0"></vue-qr>
      <h3 style="color :red">注意：支付过程中，禁止刷新关闭浏览器！支付成功后系统会自动关闭二维码！</h3>
    </el-dialog>
  </div>
</template>
<script>
import { goodsDetailList, checkout, createUser, chargeByAliPay, addOrder, readMechanismUser } from '@/api/goods'
import { queryalipaystatus } from '@/api/user'
import store from '@/store'
import VueQr from 'vue-qr'
import wxpay from '@/assets/image/wxpay.png'
import zhifubaopay from '@/assets/image/zhifubaopay.png'

export default {
  name: 'goodsDetail',
  components: { VueQr },
  data() {
    return {
      wxpay,
      zhifubaopay,
      qrDialogStatus: false,
      alipayDialogStatus: false,
      values: undefined,
      productList: null,
      info: {
        name: '',
        retailPrice: '',
        brief: ''
      },
      listQuery: {
        orderId: 0
      },
      listQuery_1: {
        page: 1,
        limit: 20,
        mechanismId: store.getters.mechanismId,
        mobile: '',
        sort: 'modify_time',
        order: 'desc',
        id: 0,
        number: 0
      },
      pic: '',
      pic_1: '',
      specifications: '',
      selectBoxIndex: 0,
      walletRecoed: {
        userId: undefined,
        recordSn: '',
        modifyAmount: '',
        modifyResource: store.getters.mechanismId,
        payType: '2',
        type: '6',
        specifications: '',
        number: ''
      },
      dialogChargeFormVisible: false,
      number: 1,
      freight: 0,
      addnumber: 0,
      minnumber: 0,
      maxnumber: 0,
      address: '',
      chargeButton: false,
      qrConfig: {
        value: ''
      },
      aliQrConfig: {
        value: ''
      },
      finalpic: '',
      finalProductId: '',
      finalSpecifications: '',
      orderSn: {
        orderSn: '',
        goodId: '',
        userId: '',
        goodsprice: ''
      }
    }
  },
  computed: {
    addListen() {
      if (this.number === this.maxnumber) {
        return (this.isdisabled = true)
      }
      if (this.maxnumber === 0) {
        return (this.isdisabled = true)
      }
    },
    minusListen() {
      if (this.number === 1) {
        return (this.isdisabled = true)
      }
      if (this.number === this.minnumber) {
        return (this.isdisabled = true)
      }
      if (this.minnumber > this.maxnumber && this.number === this.maxnumber) {
        return (this.isdisabled = true)
      }
    }
  },
  created() {
    this.listQuery.orderId = this.$route.params.orderId
    this.goodsDetailList()
    this.checkCookie()
  },
  methods: {
    goodsDetailList() {
      this.listLoading = true
      goodsDetailList(this.listQuery)
        .then(response => {
          this.info = response.data.data.info
          this.pic = this.info.picUrl
          this.pic_1 = this.info.picUrl
          this.productList = response.data.data.productList
          this.finalProductId = this.productList[0].id
          this.walletRecoed.specifications = this.productList[0].specifications.toString()
          this.info.retailPrice = this.productList[0].price
          this.number = this.info.minNumber
          this.addnumber = this.info.addNumber
          this.minnumber = this.info.minNumber
          if (this.info.minNumber === 0 || this.info.minNumber == null) {
            this.number = 1
            this.minnumber = 1
          }
          if (this.info.addNumber === 0 || this.info.addNumber == null) {
            this.addnumber = 1
          }
          this.maxnumber = this.productList[0].number
          if (this.minnumber >= this.maxnumber) {
            this.number = this.maxnumber
          }
          if (this.number === 0) {
            this.number = 1
          }
          this.listLoading = false
        })
        .catch(() => {
          this.info = {}
          this.productList = []
          this.listLoading = false
        })
    },
    select(index) {
      this.selectBoxIndex = index * 3
      this.info.retailPrice = this.productList[index].price
      this.finalpic = this.productList[index].url
      this.finalProductId = this.productList[index].id
      this.walletRecoed.specifications = this.productList[index].specifications
      this.maxnumber = this.productList[index].number
      this.number = this.info.minNumber
      if (this.info.minNumber === 0 || this.info.minNumber == null) {
        this.number = 1
        this.minnumber = 1
      }
      if (this.info.addNumber === 0 || this.info.addNumber == null) {
        this.addnumber = 1
      }
      if (this.maxnumber === 0 || this.info.addNumber == null) {
        this.number = 1
      }
      if (this.minnumber >= this.maxnumber) {
        this.number = this.maxnumber
      } else {
        this.number = this.info.minNumber
      }
      if (this.number === 0) {
        this.number = 1
      }
    },
    minus() {
      this.number = this.number - this.addnumber
      if (this.number < this.minnumber) {
        if (this.minnumber > this.maxnumber) {
          this.number = this.maxnumber
        } else {
          this.number = this.minnumber
        }
      }
    },
    add() {
      this.number = this.number + this.addnumber
      if (this.number > this.maxnumber) {
        this.number = this.maxnumber
      }
    },
    showBigImg(index) {
      this.pic = index
    },
    confirmPay() {
      this.listQuery_1.id = this.finalProductId
      this.listQuery_1.number = this.number
      readMechanismUser(this.listQuery_1).then(response => {
        const numbers = this.number
        if (numbers === null || numbers === '' || numbers === undefined) {
          this.$message.info('请填写商品数量')
          this.$refs.content.focus()
        } else if (this.maxnumber === 0) {
          this.$message.info('该规格商品已经没有库存')
        } else if (numbers > this.maxnumber) {
          this.$message.info('商品数量超过库存，请重新填写')
          this.$refs.content.focus()
        } else {
          if (response.data.data.num > 0) {
            this.freight = response.data.data.freightPrice
            this.walletRecoed.modifyAmount = response.data.data.checkedGoodsPrice
            this.dialogChargeFormVisible = true
            // this.walletRecoed.userId = response.data.data.user.id
            this.walletRecoed.recordSn = this.createRecordSn()
            this.values = response.data.data.values
          } else {
            this.$alert('用户不存在', '提示', {
              confirmButtonText: '确定'
            })
          }
        }
      })
    },
    createRecordSn() {
      var date = new Date()
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      var ss = date.getMilliseconds()
      if (ss < 10) {
        ss = '00' + ss
      } else if (ss < 100) {
        ss = '0' + ss
      }
      return (
        'JG' + Y.toString() + M.toString() + D.toString() + h.toString() + m.toString() + s.toString() + ss.toString()
      )
    },
    handleChargeCancel() {
      clearTimeout(this.timeOut)
      this.chargeButton = false
      this.dialogChargeFormVisible = false
    },
    handleCharge() {
      checkout(this.listQuery_1)
        .then(response => {
          const message = response.data.data.message
          if (message === '0') {
            this.$confirm('用户地址不存在，是否前去新增地址？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push({ name: 'mechanism' })
            })
          } else {
            this.orderSn.goodId = this.listQuery.orderId
            // this.orderSn.userId = response.data.data.user.id
            this.orderSn.goodsprice = this.info.retailPrice * this.number
            this.orderSn.orderSn = this.walletRecoed.recordSn
            // 生成订单
            addOrder({
              orderSn: this.orderSn.orderSn,
              goodId: this.orderSn.goodId,
              mechanismId: this.listQuery_1.mechanismId,
              freight: this.freight,
              goodsprice: this.orderSn.goodsprice,
              finalProductId: this.finalProductId,
              goodsname: this.info.name,
              goodsSn: this.info.goodsSn,
              number: this.number
            }).then(response => {
              console.log(response.data.data)
              if (this.walletRecoed.payType === '2') {
                this.chargeButton = true
                this.fullscreenLoading = true
                createUser(this.walletRecoed).then(response => {
                  var codeUrl = response.data.data.codeURL
                  this.qrConfig.value = codeUrl
                  this.qrDialogStatus = true
                  this.timeOut = setTimeout(() => {
                    this.checkChargeStatus()
                  }, 5000)
                })
              } else if (this.walletRecoed.payType === '1') {
                chargeByAliPay(this.walletRecoed)
                  .then(response => {
                    var data = response.data
                    if (data.errno === 0) {
                      var codeUrl = data.data
                      this.aliQrConfig.value = codeUrl
                      this.alipayDialogStatus = true
                      this.chargeButton = true
                      this.timeOut = setTimeout(() => {
                        this.checkAliPayStatus()
                      }, 5000)
                    }
                  })
                  .catch(err => {
                    console.log(err)
                  })
              }
            })
          }
        })
        .catch(() => {})
    },
    checkChargeStatus() {
      if (this.walletRecoed.recordSn !== '') {
        queryalipaystatus(this.orderSn).then(response => {
          var orderStatus = response.data.data.orderStatus
          if (orderStatus === 'SUCCESS') {
            this.qrConfig.value = ''
            this.qrDialogStatus = false
            this.timeOut = ''
            this.dialogChargeFormVisible = false
            this.fullscreenLoading = false
            this.chargeButton = false
            this.$confirm('付款成功！', '提示', {
              confirmButtonText: '查询订单',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.push({ name: 'order', params: { orderSn: this.orderSn.orderSn }})
            })
          } else {
            this.timeOut = setTimeout(() => {
              this.checkChargeStatus()
            }, 3000)
          }
        })
      }
    },
    checkAliPayStatus() {
      if (this.walletRecoed.recordSn !== '') {
        queryalipaystatus(this.orderSn)
          .then(response => {
            var orderStatus = response.data.data.orderStatus
            if (orderStatus === 'SUCCESS') {
              this.timeOut = ''
              this.aliQrConfig.value = ''
              this.dialogChargeFormVisible = false
              this.alipayDialogStatus = false
              this.fullscreenLoading = false
              this.chargeButton = false
              this.$confirm('付款成功！', '提示', {
                confirmButtonText: '查询订单',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$router.push({ name: 'order', params: { orderSn: this.orderSn.orderSn }})
              })
            } else if (orderStatus === 'WAIT_PAY') {
              this.timeOut = setTimeout(() => {
                this.checkAliPayStatus()
              }, 3000)
            }
          })
          .catch(() => {
            this.timeOut = ''
            this.dialogChargeFormVisible = false
            this.alipayDialogStatus = false
            this.fullscreenLoading = false
            this.chargeButton = false
            this.$alert('付款失败！', '提示', {
              confirmButtonText: '确定'
            })
          })
      }
    },
    setCookie: function(cname, cvalue, exdays) {
      var d = new Date()
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000)
      var expires = 'expires=' + d.toUTCString()
      console.info(cname + '=' + cvalue + '; ' + expires)
      document.cookie = cname + '=' + cvalue + '; ' + expires
      console.info(document.cookie)
    },
    getCookie: function(cname) {
      var name = cname + '='
      var ca = document.cookie.split(';')
      for (var i = 0; i < ca.length; i++) {
        var c = ca[i]
        while (c.charAt(0) === ' ') c = c.substring(1)
        if (c.indexOf(name) !== -1) return c.substring(name.length, c.length)
      }
      return ''
    },
    clearCookie: function() {
      this.setCookie('username', '', -1)
    },
    checkCookie: function() {
      if (this.$route.params.orderId === undefined) {
        const orderId = this.getCookie('orderId')
        this.listQuery.orderId = orderId
      } else {
        this.setCookie('orderId', this.$route.params.orderId, 1)
      }
    }
  }
}
</script>
<style scoped>
.item-detail-show {
  width: 80%;
  margin: 15px auto;
  display: flex;
  flex-direction: row;
  background-color: #fff;
}
.item-detail-left {
  width: 350px;
  margin-right: 60px;
}
.item-detail-big-img {
  width: 382px;
  height: 382px;
  box-shadow: 0px 0px 8px #ccc;
  cursor: pointer;
}
.item-detail-big-img img {
  width: 100%;
  height: 100%;
}
.item-detail-img-row {
  float: left;
  width: 400px;
  margin-top: 15px;
  /* display: flex; */
  /* flex-direction: row; */
  /* justify-content: space-between; */
}
.item-detail-img-small {
  float: left;
  width: 68px;
  height: 68px;
  box-shadow: 0px 0px 8px #ccc;
  cursor: pointer;
  margin: 0px 10px 10px 0px;
}
.item-detail-img-small img {
  width: 68px;
  height: 68px;
}
.item-detail-right {
  display: flex;
  flex-direction: column;
  margin-top: -15px;
}
.item-detail-title p {
  color: #666;
  font-size: 20px;
}
.item-detail-price-row {
  padding: 5px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  background-color: #f3f3f3;
}
.item-price-left {
  display: flex;
  flex-direction: column;
}
.item-price-title {
  color: #999999;
  font-size: 14px;
  margin-right: 15px;
}
.item-price-row {
  margin: 5px 0px;
}
.item-price {
  color: #e4393c;
  font-size: 23px;
  cursor: pointer;
}
.item-remarks-sum {
  padding-left: 8px;
  border-left: 1px solid #ccc;
}
.item-remarks-sum p {
  color: #999999;
  font-size: 12px;
  line-height: 10px;
  text-align: center;
}
.item-select {
  display: flex;
  flex-direction: row;
  margin-top: 15px;
}
.item-select-title {
  color: #999999;
  font-size: 14px;
  margin-right: 15px;
}
.item-select-column {
  display: flex;
  flex-direction: column;
}
.item-select-box {
  width: 200px;
  display: flex;
  flex-direction: row;
  align-items: center;
}
.item-simple {
  width: 300px;
  height: 75px;
  text-align: left;
  padding: 0px;
  margin: -3px 0px 0px 0px;
}
.item-select-img {
  width: 36px;
}
.item-select-box {
  padding: 5px;
  margin-right: 8px;
  background-color: #f7f7f7;
  border: 0.5px solid #ccc;
  cursor: pointer;
}
.item-select-box:hover {
  border: 0.5px solid #e3393c;
}
.item-select-box-active {
  border: 0.5px solid #e3393c;
}
.item-select-img img {
  width: 100%;
}
.item-select-intro p {
  margin: 0px;
  padding: 5px;
}
.item-select-class {
  padding: 5px;
  margin-right: 8px;
  background-color: #f7f7f7;
  border: 0.5px solid #ccc;
  cursor: pointer;
}
.item-select-class:hover {
  border: 0.5px solid #e3393c;
}
.add-buy-car-box {
  width: 100%;
  margin-top: 48px;
  /* border-top: 1px dotted #ccc; */
}
.add-buy-car {
  margin-top: 15px;
}
.abimg {
  position: absolute;
  margin-top: -15px;
  height: 40px;
}
.rra {
  margin-left: 200px;
}
</style>
